<template>
  <el-card class="box-card">
    <h2 class="titleHeader">
      {{ route.query.id ? '修改图书' : '发布图书' }}
      <div class="headerRight">
        <el-select v-model="lableNameData" class="m-2" placeholder="默认草稿">
          <el-option
            v-for="item in store.state.lableData"
            :key="item._id"
            :label="item.labelName"
            :value="item.labelName"
          />
        </el-select>
        <SendBtn @click="handleSend">send</SendBtn>
      </div>
    </h2>
    <el-input v-model="articleTitle" placeholder="请输入图书标题" clearable />
    <TinymceEditor ref="Editor" :updateHtml="updateHtml"></TinymceEditor>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, onBeforeUnmount, inject, defineAsyncComponent } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import {
  postArticle,
  getArticleSingle,
  updateArticle,
} from '@/utils/articleHttp'
const TinymceEditor = defineAsyncComponent(
  () => import('@/components/article/TinymceEditor.vue')
)
const SendBtn = defineAsyncComponent(
  () => import('@/components/button/SendBtn.vue')
)

// 传入的要更新的html
const updateHtml = ref('')
// 全局状态
const store: any = inject('store')
// 分类标签
store.GetLableData() // 获取分类标签 有就return了
// 编辑框
const Editor = ref()
// 图书标题
const articleTitle = ref<string>('')
articleTitle.value = dayjs(new Date()).format('YYYY-MM-DD HH:mm')
// 引入路由
const route = useRoute()
const router = useRouter()
const lableNameData = ref<string>('')
// 是否是更新的图书
const updateArticleFlag: Boolean = !!route.query.id
// 原始的标签
let oldlableName: string
// 更新的就有id 先存起来不能用路由跳转的时候就没了
let updateArticleId = route.query.id as string | undefined
// 如果有query id就发请求
const getUpdateData = () => {
  getArticleSingle(updateArticleId).then((res) => {
    articleTitle.value = res.data.info[0].title
    lableNameData.value = res.data.info[0].articleType
    oldlableName = res.data.info[0].articleType // 传给oldLableName
    updateHtml.value = res.data.info[0].info
  })
}

updateArticleFlag && getUpdateData()

// 提交
const handleSend = async () => {
  if (!articleTitle.value.trim()) return ElMessage.error('标题不能为空')
  const labelName = lableNameData.value || '草稿'
  ;(Editor.value as { deletImage: () => void }).deletImage() // 触发删除图片函数
  let res
  if (updateArticleFlag) {
    // 修改的逻辑
    res = await updateArticle(
      updateArticleId,
      articleTitle.value,
      Editor.value.valueHtml,
      labelName,
      Editor.value.bg
    )
    // 删除旧的labelName
    store.subtractLableArticle(oldlableName)
  } else {
    // 提交的逻辑
    res = await postArticle(
      articleTitle.value,
      Editor.value.valueHtml,
      Editor.value.bg,
      labelName
    )
  }
  // 对应的图书数量加1
  store.addLableArticle(labelName)
  res.data.ok
    ? ElMessage.success(res.data.info)
    : ElMessage.error(res.data.info)
  // 清空那个数组以防多次触发保存
  Editor.value && Editor.value.clearHtml()
  router.replace('/home/article/article-list')
}
// 当组件销毁的时候触发
onBeforeUnmount(() => {
  window.onbeforeunload = null
  Editor.value.InsertionImages.length && handleSend()
})
// 当页面刷新的时候执行
window.onbeforeunload = () => {
  Editor.value.InsertionImages.length && handleSend()
}
</script>

<style lang="scss" scoped>
.titleHeader {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.m-2 {
  width: 100px;
}

.headerRight {
  display: flex;
}
</style>
